package cn.kgc.day05.dao.impl;

import cn.kgc.day05.dao.UserDao;
import cn.kgc.day05.entity.User;
import cn.kgc.day05.util.JDBCUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

/**
 * @author 课工场
 * @date 2024/10/16
 * @description
 */
public class UserDaoImpl implements UserDao {


    @Override
    public User selectByUsername(String username) {
        QueryRunner queryRunner = new QueryRunner(JDBCUtil.getDataSource());
        String sql = "select * from user where username = ?";

        try {
            User user = queryRunner.query(sql, new BeanHandler<User>(User.class), username);
            return  user;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void registerUser(String username, String md5Pwd) {

        QueryRunner queryRunner = new QueryRunner(JDBCUtil.getDataSource());
        String sql = "insert into user (username,password) values(?,?)";
        try {
            int update = queryRunner.update(sql, username, md5Pwd);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public User selectByUsernameAndPwd(String username, String md5pwd) {

        QueryRunner queryRunner = new QueryRunner(JDBCUtil.getDataSource());
        String sql = "select * from user where username = ? and password = ?";
        try {
            User query = queryRunner.query(sql, new BeanHandler<User>(User.class), username, md5pwd);
            return query;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updatePersonalInfo(User user) {
        QueryRunner queryRunner = new QueryRunner(JDBCUtil.getDataSource());
        String sql = "update user set sex = ? ,tel = ? ,age = ? where id = ?";
        try {
            int update = queryRunner.update(sql, user.getSex(), user.getTel(), user.getAge(),user.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updatePersonalPwd(String username, String md5NewPwd) {

        QueryRunner queryRunner = new QueryRunner(JDBCUtil.getDataSource());
        String sql = "update user set password =? where username = ?";
        try {
            queryRunner.update(sql,md5NewPwd,username);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
